package com.bugstack.domain.activity.service.paytake;

import com.bugstack.domain.activity.model.aggregate.CreatePartakeOrderAggregate;
import com.bugstack.domain.activity.model.entity.*;
import com.bugstack.domain.activity.model.valobj.UserRaffleOrderStateVO;
import com.bugstack.domain.activity.reopsitory.IActivityRepository;
import com.bugstack.domain.activity.service.paytake.threadTask.QueryActivityAccountDayTask;
import com.bugstack.domain.activity.service.paytake.threadTask.QueryActivityAccountMonthTask;
import com.bugstack.domain.activity.service.paytake.threadTask.QueryRaffleActivityAccountTask;
import com.bugstack.types.enums.ResponseCode;
import com.bugstack.types.exception.AppException;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: czb
 * @Description: TODO
 * @DateTime: 2025/3/25 16:43
 **/
@Service
public class ActivityPayTakeService extends AbstractActivityPayTakeService {

    private final SimpleDateFormat dateFormatMonth = new SimpleDateFormat("yyyy-MM");
    private final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    protected ActivityPayTakeService(IActivityRepository activityRepository) {
        super(activityRepository);
    }

    @Override
    protected UserRaffleOrderEntity createUserRaffleOrder(String userId, ActivityEntity activity, Date currentDate) {
        // 构建订单
        UserRaffleOrderEntity userRaffleOrder = new UserRaffleOrderEntity();
        userRaffleOrder.setUserId(userId);
        userRaffleOrder.setActivityId(activity.getActivityId());
        userRaffleOrder.setActivityName(activity.getActivityName());
        userRaffleOrder.setStrategyId(activity.getStrategyId());
        userRaffleOrder.setOrderId(RandomStringUtils.randomNumeric(12));
        userRaffleOrder.setOrderTime(currentDate);
        userRaffleOrder.setState(UserRaffleOrderStateVO.create);
        userRaffleOrder.setEndDateTime(activity.getEndDateTime());
        return userRaffleOrder;
    }

    @Override
    protected CreatePartakeOrderAggregate doFilterAccount(Long activityId, String userId, Date currentDate) throws ExecutionException, InterruptedException {
        ActivityAccountMonthEntity activityAccountMonthEntity;
        ActivityAccountDayEntity activityAccountDayEntity;
        ActivityAccountEntity activityAccountEntity;

        String month = dateFormatMonth.format(currentDate);
        String day = dateFormatDay.format(currentDate);

        Future<ActivityAccountEntity> queryRaffleActivityAccountTask = threadPoolExecutor.submit(new QueryRaffleActivityAccountTask(activityId, userId, activityRepository));
        Future<ActivityAccountMonthEntity> queryActivityAccountMonthTask = threadPoolExecutor.submit(new QueryActivityAccountMonthTask(activityId, userId, month, activityRepository));
        Future<ActivityAccountDayEntity> queryActivityAccountDayTask = threadPoolExecutor.submit(new QueryActivityAccountDayTask(activityId, userId, day, activityRepository));

        activityAccountEntity = queryRaffleActivityAccountTask.get();
        activityAccountMonthEntity = queryActivityAccountMonthTask.get();
        activityAccountDayEntity = queryActivityAccountDayTask.get();


        // 额度判断（只判断总剩余额度）
        if (null == activityAccountEntity || activityAccountEntity.getTotalCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
        }

        boolean isExistAccountMonth = activityAccountMonthEntity != null;
        if (isExistAccountMonth && activityAccountMonthEntity.getMonthCountSurplus() <= 0)
            throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());

        //月账号不存在，构造月账户
        if (!isExistAccountMonth) {
            activityAccountMonthEntity = new ActivityAccountMonthEntity();
            activityAccountMonthEntity.setActivityId(activityId);
            activityAccountMonthEntity.setMonth(month);
            activityAccountMonthEntity.setUserId(userId);
            activityAccountMonthEntity.setMonthCount(activityAccountEntity.getMonthCount());
            activityAccountMonthEntity.setMonthCountSurplus(activityAccountEntity.getMonthCountSurplus());
        }

        boolean isExistAccountDay = activityAccountDayEntity != null;
        if (isExistAccountDay && activityAccountMonthEntity.getMonthCountSurplus() <= 0)
            throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo());

        //月账号不存在，构造月账户
        if (!isExistAccountDay) {
            activityAccountDayEntity = new ActivityAccountDayEntity();
            activityAccountDayEntity.setActivityId(activityId);
            activityAccountDayEntity.setDay(day);
            activityAccountDayEntity.setUserId(userId);
            activityAccountDayEntity.setDayCount(activityAccountEntity.getDayCount());
            activityAccountDayEntity.setDayCountSurplus(activityAccountEntity.getDayCountSurplus());
        }

        //聚合对象
        CreatePartakeOrderAggregate createPartakeOrderAggregate = new CreatePartakeOrderAggregate();
        createPartakeOrderAggregate.setUserId(userId);
        createPartakeOrderAggregate.setActivityId(activityId);
        createPartakeOrderAggregate.setActivityAccountEntity(activityAccountEntity);
        createPartakeOrderAggregate.setActivityAccountMonthEntity(activityAccountMonthEntity);
        createPartakeOrderAggregate.setActivityAccountDayEntity(activityAccountDayEntity);
        createPartakeOrderAggregate.setExistAccountDay(isExistAccountDay);
        createPartakeOrderAggregate.setExistAccountMonth(isExistAccountMonth);

        return createPartakeOrderAggregate;
    }
}
